from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from course.apps import CourseConfig
from course.models import CourseModel01
from course.ser import CourseSer
from home.models import NavModel, BannerModel, CategoryModel
from home.ser import NavSer, BannerSer, Category, CategorySer


# Create your views here.
class HomeView(APIView):
    def get(self,request):
        return Response("ok")

class TopNavView(APIView):
    def get(self,request):
        navs = NavModel.objects.filter(position=True,is_del=False).order_by('order')
        ser = NavSer(instance=navs,many=True)
        return Response({"msg":"ok","code":"200","data":ser.data})

class FootNavView(APIView):
    def get(self,request):
        navs = NavModel.objects.filter(position=False,is_del=False).order_by('order')
        ser = NavSer(instance = navs, many = True)
        return Response({"msg":"ok","code":"200","data":ser.data})

class BannerView(APIView):
    def get(self,request):
        banner = BannerModel.objects.filter(is_del=False).order_by('order')
        ser = BannerSer(instance=banner,many=True)
        return Response({"msg":"ok","code":"200","data":ser.data})
class CategoryView(APIView):
    def get(self,request):
        category = CategoryModel.objects.filter(is_del=False,parent=None,is_home=True).order_by('order')
        ser = CategorySer(instance=category,many=True)
        for i in ser.data:
            i['children'] = i['children'][:3]
        return Response({"msg":"ok","code":200,"data":ser.data})

class NoCategoryView(APIView):
    def get(self,request):
        category = CategoryModel.objects.filter(is_del=False,id = request.query_params.get("id")).first()
        ser = CategorySer(instance=category)
        courses = CategoryModel.objects.filter(is_del=False,parent=request.query_params.get('id'))
        cateList = []
        for i in courses:
            cateList.append(i.id)
        allcourse = CourseModel01.objects.filter(is_del=False,category__in=cateList,is_home=True).order_by('order')
        ser2 = CourseSer(instance=allcourse,many = True)
        mdata = ser.data
        mdata['courses'] = ser2.data[:4]
        return Response({"msg":"ok","code":200,"data":mdata})


